<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>optional的使用 | 若愚湖畔</title><meta name="keywords" content="java"><meta name="author" content="albafica"><meta name="copyright" content="albafica"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="概述写程序过程中，不可避免会遇到的NPE问题。为了避免这类问题，很多时候会引入大量的if...else代码来处理。比如: 1234567if(user !&#x3D; null)&amp;#123;    if(user.getAddress() !&#x3D; null)&amp;#123;        if(user.getAddress().getCity() !&#x3D; null)&amp;#123;            return">
<meta property="og:type" content="article">
<meta property="og:title" content="optional的使用">
<meta property="og:url" content="https://albafica.gitee.io/2022/05/02/optional/index.html">
<meta property="og:site_name" content="若愚湖畔">
<meta property="og:description" content="概述写程序过程中，不可避免会遇到的NPE问题。为了避免这类问题，很多时候会引入大量的if...else代码来处理。比如: 1234567if(user !&#x3D; null)&amp;#123;    if(user.getAddress() !&#x3D; null)&amp;#123;        if(user.getAddress().getCity() !&#x3D; null)&amp;#123;            return">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="">
<meta property="article:published_time" content="2022-05-02T02:10:03.000Z">
<meta property="article:modified_time" content="2022-05-02T03:40:49.817Z">
<meta property="article:author" content="albafica">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content=""><link rel="shortcut icon" href="/hexoblog/img/favicon.png"><link rel="canonical" href="https://albafica.gitee.io/2022/05/02/optional/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/hexoblog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/hexoblog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'optional的使用',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-02 11:40:49'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.1.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s1.ax1x.com/2022/04/23/Lhpz3F.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/hexoblog/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="data-item"><a href="/hexoblog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="data-item"><a href="/hexoblog/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexoblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexoblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/hexoblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexoblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/hexoblog/">若愚湖畔</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexoblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexoblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/hexoblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexoblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">optional的使用</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-02T02:10:03.000Z" title="发表于 2022-05-02 10:10:03">2022-05-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-02T03:40:49.817Z" title="更新于 2022-05-02 11:40:49">2022-05-02</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>写程序过程中，不可避免会遇到的NPE问题。为了避免这类问题，很多时候会引入大量的<code>if...else</code>代码来处理。比如:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(user != <span class="literal">null</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(user.getAddress() != <span class="literal">null</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(user.getAddress().getCity() != <span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> user.getAddress().getCity();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这类代码最大的问题就是比较丑陋。为此java8中设计了<code>Optional</code>来优化这类写法。</p>
<blockquote>
<p>但不得不说，虽然上述代码看起来比较丑陋，但这类代码属于任何层次的人都能读懂，如果业务逻辑特别复杂，我个人倾向于用简单方案实现，虽然代码丑了点，但相比于Optional这种链式操作，出错的概率会降低很多.</p>
</blockquote>
<h2 id="API介绍"><a href="#API介绍" class="headerlink" title="API介绍"></a>API介绍</h2><h3 id="1-Optional-T-value-empty-of-T-value-ofNullable-T-value"><a href="#1-Optional-T-value-empty-of-T-value-ofNullable-T-value" class="headerlink" title="1. Optional(T value), empty(), of(T value), ofNullable(T value)"></a>1. <code>Optional(T value), empty(), of(T value), ofNullable(T value)</code></h3><p>这四个函数比较相似，<code>Optional(T value)</code>是<code>private</code>的构造函数，不能外部调用。其余是<code>public</code>de 。那么<code>Optional</code>本质就是内存存储一个真实的值，构造的时候，直接判断是否为空，而<code>empty()</code>则是返回一个空值对象。</p>
<p>这几个方法的的源码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> T value;</span><br><span class="line"><span class="keyword">private</span> <span class="title function_">Optional</span><span class="params">(T value)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = Objects.requireNonNull(value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Optional&lt;?&gt; EMPTY = <span class="keyword">new</span> <span class="title class_">Optional</span>&lt;&gt;();</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span>&lt;T&gt; Optional&lt;T&gt; <span class="title function_">empty</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">    Optional&lt;T&gt; t = (Optional&lt;T&gt;) EMPTY;</span><br><span class="line">    <span class="keyword">return</span> t;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Optional&lt;T&gt; <span class="title function_">of</span><span class="params">(T value)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Optional</span>&lt;&gt;(value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Optional&lt;T&gt; <span class="title function_">ofNullable</span><span class="params">(T value)</span> &#123;</span><br><span class="line">    <span class="type">return</span> <span class="variable">value</span> <span class="operator">=</span>= <span class="literal">null</span> ? empty() : of(value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>构造函数结构图如下</p>
<p><img src="/hexoblog/2022/05/02/optional/img1.png" alt="img"></p>
<p>通过观察上述源码，可以得到几个结论</p>
<ul>
<li>调用<code>of(T value)</code>和<code>ofNullable(T value)</code>会调用内部构造函数</li>
<li>通过<code>of(T value)</code>构造出的<code>Optional</code>对象<ul>
<li>当<code>value</code>值为空时，依旧会抛出<code>NullPointerException</code></li>
<li>当<code>value</code>值不为空时，能正常构造<code>Optional</code>对象</li>
</ul>
</li>
<li>通过<code>ofNullable(T value)</code>构造出的<code>Optional</code>对象<ul>
<li>如果<code>value</code>不为空，能正常构造<code>Optional</code>对象</li>
<li>如果<code>value</code>为空，则返回通过<code>empty()</code>创建的<code>EMPTY</code>对象，并不会抛出<code>NullPointerException</code></li>
</ul>
</li>
</ul>
<p>所以，除非明确需要抛出<code>NPE</code>的场景，一般可以使用<code>ofNullable</code>去构建<code>Optional</code>对象.</p>
<h3 id="2-orElse-T-other-，orElseGet-Supplier-other-和orElseThrow-Supplier-exceptionSupplier"><a href="#2-orElse-T-other-，orElseGet-Supplier-other-和orElseThrow-Supplier-exceptionSupplier" class="headerlink" title="2. orElse(T other)，orElseGet(Supplier other)和orElseThrow(Supplier exceptionSupplier)"></a>2. <code>orElse(T other)，orElseGet(Supplier other)和orElseThrow(Supplier exceptionSupplier)</code></h3><p>先上源码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> T <span class="title function_">orElse</span><span class="params">(T other)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> value != <span class="literal">null</span> ? value : other;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> T <span class="title function_">orElseGet</span><span class="params">(Supplier&lt;? extends T&gt; supplier)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> value != <span class="literal">null</span> ? value : supplier.get();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> &lt;X <span class="keyword">extends</span> <span class="title class_">Throwable</span>&gt; T <span class="title function_">orElseThrow</span><span class="params">(Supplier&lt;? extends X&gt; exceptionSupplier)</span> <span class="keyword">throws</span> X &#123;</span><br><span class="line">    <span class="keyword">if</span> (value != <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">throw</span> exceptionSupplier.get();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这三个函数都是当传入值为<code>null</code>时调用，首先是<code>orElseThrow</code>,这个最简单，上面提到使用<code>of(T value)</code>去构造<code>Optional</code>对象，抛出的是<code>NPE</code>异常，通过这个我们可以自定义异常，这也是为啥上面说一般不直接使用<code>of</code>去构造。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">Optional.ofNullable(user).orElseThrow(()-&gt;<span class="keyword">new</span> <span class="title class_">CommonException</span>(<span class="string">&quot;用户不存在&quot;</span>));</span><br></pre></td></tr></table></figure>

<p>然后是<code>orElse(t other)</code>和<code>orElseGet(Supplier&lt;? extends T&gt; supplier)</code>,这两个函数意思时如果传入为null则使用另一个值替代，等同于给一个默认值，差别是入参。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    user = Optional.ofNullable(user).orElse(createUser());</span><br><span class="line">    user = Optional.ofNullable(user).orElseGet(() -&gt; createUser());</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> User <span class="title function_">createUser</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">    user.setName(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-map-Function-mapper-和flatMap-Function-gt-mapper"><a href="#3-map-Function-mapper-和flatMap-Function-gt-mapper" class="headerlink" title="3. map(Function mapper)和flatMap(Function&gt; mapper)"></a>3. <code>map(Function mapper)和flatMap(Function&gt; mapper)</code></h3><p>这两个函数是做转换值操作的,还是上源码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;U&gt; Optional&lt;U&gt; <span class="title function_">map</span><span class="params">(Function&lt;? <span class="built_in">super</span> T, ? extends U&gt; mapper)</span> &#123;</span><br><span class="line">    Objects.requireNonNull(mapper);</span><br><span class="line">    <span class="keyword">if</span> (!isPresent()) &#123;</span><br><span class="line">        <span class="keyword">return</span> empty();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> Optional.ofNullable(mapper.apply(value));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> &lt;U&gt; Optional&lt;U&gt; <span class="title function_">flatMap</span><span class="params">(Function&lt;? <span class="built_in">super</span> T, ? extends Optional&lt;? extends U&gt;&gt; mapper)</span> &#123;</span><br><span class="line">    Objects.requireNonNull(mapper);</span><br><span class="line">    <span class="keyword">if</span> (!isPresent()) &#123;</span><br><span class="line">        <span class="keyword">return</span> empty();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">        Optional&lt;U&gt; r = (Optional&lt;U&gt;) mapper.apply(value);</span><br><span class="line">        <span class="keyword">return</span> Objects.requireNonNull(r);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这两个函数，在函数体上没什么区别。唯一区别的就是入参，map函数所接受的入参类型为<code>Function&lt;? super T, ? extends U&gt;</code>，而flapMap的入参类型为<code>Function&lt;? super T, Optional&lt;U&gt;&gt;</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> Optional&lt;String&gt; <span class="title function_">getNameOptional</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> Optional.ofNullable(name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">String</span> <span class="variable">city</span> <span class="operator">=</span> Optional.ofNullable(user).map(u-&gt; u.getName()).get();</span><br><span class="line"><span class="type">String</span> <span class="variable">city</span> <span class="operator">=</span> Optional.ofNullable(user).flatMap(u-&gt; u.getNameOptional()).get();</span><br></pre></td></tr></table></figure>

<h3 id="4-isPresent-和ifPresent-Consumer-consumer"><a href="#4-isPresent-和ifPresent-Consumer-consumer" class="headerlink" title="4.isPresent()和ifPresent(Consumer consumer)"></a>4.<code>isPresent()和ifPresent(Consumer consumer)</code></h3><p>这两个函数是对值为空的处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">isPresent</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> value != <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">ifPresent</span><span class="params">(Consumer&lt;? <span class="built_in">super</span> T&gt; action)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (value != <span class="literal">null</span>) &#123;</span><br><span class="line">        action.accept(value);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-filter-Predicate-predicate"><a href="#5-filter-Predicate-predicate" class="headerlink" title="5. filter(Predicate predicate)"></a>5. <code>filter(Predicate predicate)</code></h3><p>filter 方法接受一个 Predicate 来对 Optional 中包含的值进行过滤，如果包含的值满足条件，那么还是返回这个 Optional；否则返回 Optional.empty。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> Optional&lt;T&gt; <span class="title function_">filter</span><span class="params">(Predicate&lt;? <span class="built_in">super</span> T&gt; predicate)</span> &#123;</span><br><span class="line">    Objects.requireNonNull(predicate);</span><br><span class="line">    <span class="keyword">if</span> (!isPresent()) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> predicate.test(value) ? <span class="built_in">this</span> : empty();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>用法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;User&gt; user1 = Optional.ofNullable(user).filter(u -&gt; u.getName().length()&lt;<span class="number">6</span>);</span><br></pre></td></tr></table></figure>

<h2 id="实战使用"><a href="#实战使用" class="headerlink" title="实战使用"></a>实战使用</h2><blockquote>
<p>假定有如下结构</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Address address;</span><br><span class="line">    ...</span><br><span class="line">    getter() &amp; setter() &amp; toString()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Address</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Address</span><span class="params">(String city)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.city = city;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> String city;</span><br><span class="line">    ...</span><br><span class="line">    getter() &amp; setter() &amp; toString()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-通过Optional从一个对象中取值"><a href="#1-通过Optional从一个对象中取值" class="headerlink" title="1. 通过Optional从一个对象中取值"></a>1. 通过Optional从一个对象中取值</h3><ul>
<li><p>以前的写法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> String <span class="title function_">getCity</span><span class="params">(User user)</span>  <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">    <span class="keyword">if</span>(user!=<span class="literal">null</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(user.getAddress()!=<span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="type">Address</span> <span class="variable">address</span> <span class="operator">=</span> user.getAddress();</span><br><span class="line">            <span class="keyword">if</span>(address.getCity()!=<span class="literal">null</span>)&#123;</span><br><span class="line">                <span class="keyword">return</span> address.getCity();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Excpetion</span>(<span class="string">&quot;取值错误&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Optional的写法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> String <span class="title function_">getCity</span><span class="params">(User user)</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">    <span class="keyword">return</span> Optional.ofNullable(user)</span><br><span class="line">                   .map(u-&gt; u.getAddress())</span><br><span class="line">                   .map(a-&gt;a.getCity())</span><br><span class="line">                   .orElseThrow(()-&gt;<span class="keyword">new</span> <span class="title class_">Exception</span>(<span class="string">&quot;取值错误&quot;</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="2-入参对象不为空则进行处理逻辑"><a href="#2-入参对象不为空则进行处理逻辑" class="headerlink" title="2. 入参对象不为空则进行处理逻辑"></a>2. 入参对象不为空则进行处理逻辑</h3><ul>
<li><p>之前的写法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(user!=<span class="literal">null</span>)&#123;</span><br><span class="line">    dosomething(user);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Optional的写法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Optional.ofNullable(user)</span><br><span class="line">.ifPresent(u-&gt;&#123;</span><br><span class="line">    dosomething(u);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="3-如果传入的对象不是zhangsan则重新构造"><a href="#3-如果传入的对象不是zhangsan则重新构造" class="headerlink" title="3.如果传入的对象不是zhangsan则重新构造"></a>3.如果传入的对象不是zhangsan则重新构造</h3><ul>
<li><p>之前的写法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> User <span class="title function_">getUser</span><span class="params">(User user)</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">    <span class="keyword">if</span>(user!=<span class="literal">null</span>)&#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> user.getName();</span><br><span class="line">        <span class="keyword">if</span>(<span class="string">&quot;zhangsan&quot;</span>.equals(name))&#123;</span><br><span class="line">            <span class="keyword">return</span> user;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    user = <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">    user.setName(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Optional的写法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> User <span class="title function_">getUser</span><span class="params">(User user)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> Optional.ofNullable(user)</span><br><span class="line">                   .filter(u-&gt;<span class="string">&quot;zhangsan&quot;</span>.equals(u.getName()))</span><br><span class="line">                   .orElseGet(()-&gt; &#123;</span><br><span class="line">                        <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">                        user1.setName(<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line">                        <span class="keyword">return</span> user1;</span><br><span class="line">                   &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>使用<code>Optional</code>对象，可以省去很多<code>if...else</code>的判断，让代码通过链式的方式更加简洁，但这种简洁也一定程度上牺牲了代码的可读性。写代码，不能为了优雅而优雅，解决问题才是第一王道，而能让所有人都能能看懂并且刚改，则是第二王道。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">albafica</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://albafica.gitee.io/2022/05/02/optional/">https://albafica.gitee.io/2022/05/02/optional/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://albafica.gitee.io" target="_blank">若愚湖畔</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/hexoblog/tags/java/">java</a></div><div class="post_share"></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/hexoblog/2022/04/25/stream-api/" title="使用Stream API优化代码[转载]"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-25</div><div class="title">使用Stream API优化代码[转载]</div></div></a></div><div><a href="/hexoblog/2022/05/07/functionalinterface/" title="Function接口简单代码结构"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-07</div><div class="title">Function接口简单代码结构</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://s1.ax1x.com/2022/04/23/Lhpz3F.png" onerror="this.onerror=null;this.src='/hexoblog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">albafica</div><div class="author-info__description">Stay hungry Stay foolish</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/hexoblog/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="card-info-data-item"><a href="/hexoblog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="card-info-data-item"><a href="/hexoblog/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-number">1.</span> <span class="toc-text">概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#API%E4%BB%8B%E7%BB%8D"><span class="toc-number">2.</span> <span class="toc-text">API介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-Optional-T-value-empty-of-T-value-ofNullable-T-value"><span class="toc-number">2.1.</span> <span class="toc-text">1. Optional(T value), empty(), of(T value), ofNullable(T value)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-orElse-T-other-%EF%BC%8CorElseGet-Supplier-other-%E5%92%8CorElseThrow-Supplier-exceptionSupplier"><span class="toc-number">2.2.</span> <span class="toc-text">2. orElse(T other)，orElseGet(Supplier other)和orElseThrow(Supplier exceptionSupplier)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-map-Function-mapper-%E5%92%8CflatMap-Function-gt-mapper"><span class="toc-number">2.3.</span> <span class="toc-text">3. map(Function mapper)和flatMap(Function&gt; mapper)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-isPresent-%E5%92%8CifPresent-Consumer-consumer"><span class="toc-number">2.4.</span> <span class="toc-text">4.isPresent()和ifPresent(Consumer consumer)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-filter-Predicate-predicate"><span class="toc-number">2.5.</span> <span class="toc-text">5. filter(Predicate predicate)</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E6%88%98%E4%BD%BF%E7%94%A8"><span class="toc-number">3.</span> <span class="toc-text">实战使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E9%80%9A%E8%BF%87Optional%E4%BB%8E%E4%B8%80%E4%B8%AA%E5%AF%B9%E8%B1%A1%E4%B8%AD%E5%8F%96%E5%80%BC"><span class="toc-number">3.1.</span> <span class="toc-text">1. 通过Optional从一个对象中取值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%85%A5%E5%8F%82%E5%AF%B9%E8%B1%A1%E4%B8%8D%E4%B8%BA%E7%A9%BA%E5%88%99%E8%BF%9B%E8%A1%8C%E5%A4%84%E7%90%86%E9%80%BB%E8%BE%91"><span class="toc-number">3.2.</span> <span class="toc-text">2. 入参对象不为空则进行处理逻辑</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%A6%82%E6%9E%9C%E4%BC%A0%E5%85%A5%E7%9A%84%E5%AF%B9%E8%B1%A1%E4%B8%8D%E6%98%AFzhangsan%E5%88%99%E9%87%8D%E6%96%B0%E6%9E%84%E9%80%A0"><span class="toc-number">3.3.</span> <span class="toc-text">3.如果传入的对象不是zhangsan则重新构造</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%93%E8%AF%AD"><span class="toc-number">4.</span> <span class="toc-text">结语</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/18/techupdate/" title="技术升级简要构思">技术升级简要构思</a><time datetime="2022-05-18T12:54:43.000Z" title="发表于 2022-05-18 20:54:43">2022-05-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/07/functionalinterface/" title="Function接口简单代码结构">Function接口简单代码结构</a><time datetime="2022-05-07T10:18:48.000Z" title="发表于 2022-05-07 18:18:48">2022-05-07</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/07/cap/" title="微服务-CAP理论">微服务-CAP理论</a><time datetime="2022-05-07T01:12:07.000Z" title="发表于 2022-05-07 09:12:07">2022-05-07</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/02/optional/" title="optional的使用">optional的使用</a><time datetime="2022-05-02T02:10:03.000Z" title="发表于 2022-05-02 10:10:03">2022-05-02</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/01/pattern-overload/" title="设计模式-概述">设计模式-概述</a><time datetime="2022-05-01T10:12:20.000Z" title="发表于 2022-05-01 18:12:20">2022-05-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By albafica</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/hexoblog/js/utils.js"></script><script src="/hexoblog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="富强,民主,文明,和谐,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="false" async="async"></script></div></body></html>